package com.hbnu.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.constant.AuthorTypeConstants;
import com.hbnu.system.mapper.AchievementAuthorMapper;
import com.hbnu.system.mapper.AchievementMapper;
import com.hbnu.system.model.entity.Achievement;
import com.hbnu.system.model.entity.AchievementAuthor;
import com.hbnu.system.model.entity.Porprojectauthor;
import com.hbnu.system.model.entity.User;
import com.hbnu.system.service.AchievementAuthorService;
import com.hbnu.system.service.AchievementQualificationService;
import com.hbnu.system.service.AchievementService;
import com.hbnu.system.service.IUserService;
import com.hbnu.system.utils.CheckRoleUtil;
import com.hbnu.system.utils.IdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (AchievementAuthor)表服务实现类
 *
 * @author makejava
 * @since 2025-07-22 19:14:16
 */
@Service
public class AchievementAuthorServiceImpl extends ServiceImpl<AchievementAuthorMapper, AchievementAuthor> implements AchievementAuthorService {
    @Autowired
    private AchievementService iAchievementService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private CheckRoleUtil checkRoleUtil;

    @Autowired
    private AchievementQualificationService iAchievementQualificationService;

    @Autowired
    private AchievementMapper achievementMapper;

    private static final List<String> AUTHOR_TYPE_ORDER = Arrays.asList(
            "第一作者", "共同第一作者", "通讯作者", "第二作者", "第三作者", "其他排名"
    );

    // 用于保留两位小数的格式化器
    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.00");

    /**
     * 添加科研成果作者
     * @param achievementAuthor 科研成果作者信息
     * @return 添加操作是否成功
     */
    @Override
    public boolean addAchievementAuthor(AchievementAuthor achievementAuthor) {
        // 不使用前端传过来的id，生成新id
        achievementAuthor.setAchievementAuthorId(null);
        Achievement achievement = achievementMapper.selectById(achievementAuthor.getAchievementId());
        checkRoleUtil.checkPermissionAchievement(achievement.getStatus());

        //如果是校外作者或者学生，为其生成工号
        if (achievementAuthor.getPeopleType().equals(AuthorTypeConstants.OUT_SCHOOL_AUTHOR)
                ||achievementAuthor.getPeopleType().equals(AuthorTypeConstants.STUDENT)) {
            achievementAuthor.setUserAccount(IdGenerator.generateId());
        }

        // 检查工号是否为空
        if (achievementAuthor.getUserAccount().isEmpty()) {
            throw new BaseException("请输入工号");
        }

        // 检查是否重复添加
        AchievementAuthor existingAuthor = getOne(
                Wrappers.lambdaQuery(AchievementAuthor.class)
                        .eq(AchievementAuthor::getAchievementId, achievementAuthor.getAchievementId())
                        .eq(AchievementAuthor::getUserAccount, achievementAuthor.getUserAccount())
        );
        if (Objects.nonNull(existingAuthor)) {
            throw new BaseException("不可重复添加");
        }

        // 检查考核系数(支持整数和小数)
        double newAssessment;
        try {
            newAssessment = Double.parseDouble(achievementAuthor.getAssessment());
        } catch (NumberFormatException e) {
            throw new BaseException("考核系数格式不正确");
        }
        if (newAssessment < 0 || newAssessment > 100) {
            throw new BaseException("考核系数应在 0 到 100 之间");
        }

        String Pscore = "0.00";

//        Achievement_Qualification achievementQualification = iAchievementQualificationService.getById(achievementAuthor.getAchievementID());

//        if(achievement.getScore() != null){
//            System.out.println("12123");
//            float finalValue = Float.parseFloat(achievement.getScore());
//            // 计算并保留两位小数
//            double pscore = finalValue * newAssessment / 100.0;
//            Pscore = DECIMAL_FORMAT.format(pscore);
//        }

        String scoreStr = achievement.getScore();
        if (scoreStr != null && !scoreStr.trim().isEmpty()) {
            try {
                float finalValue = Float.parseFloat(scoreStr.trim());
                double pscore = finalValue * newAssessment / 100.0;
                Pscore = DECIMAL_FORMAT.format(pscore);
            } catch (NumberFormatException e) {
                Pscore = "0.00";
            }
        } else {
            Pscore = "0.00";
        }

        // 计算考核系数总和
        List<AchievementAuthor> authors = list(
                Wrappers.lambdaQuery(AchievementAuthor.class)
                        .eq(AchievementAuthor::getAchievementId, achievementAuthor.getAchievementId())
        );
        for (AchievementAuthor author : authors){
            if(author.getAssessment().equals("")){
                throw new BaseException("请补全所有作者考核系数");
            }
        }
        Double totalAssessment = authors.stream()
                .mapToDouble(author -> Double.parseDouble(author.getAssessment()))
                .sum();
        if (totalAssessment + newAssessment > 100) {
            throw new BaseException("作者考核系数总和大于100!");
        }

        achievementAuthor.setPscore(Pscore);

        boolean result = save(achievementAuthor);
        if (result) {
            updateAllAuthor(achievement, achievementAuthor);
        }
        return result;
    }

    /**
     * 删除科研成果作者
     * @param id 作者ID
     * @return 删除操作是否成功
     */
    @Override
    public boolean deleteAchievementAuthor(String id) {
        AchievementAuthor achievementAuthor = super.getOne(Wrappers.lambdaQuery(AchievementAuthor.class)
                .eq(AchievementAuthor::getAchievementAuthorId, id));
        if (Objects.isNull(achievementAuthor)) {
            throw new BaseException("不存在关联作者");
        }

        Achievement achievement = iAchievementService.getOne(Wrappers.lambdaQuery(Achievement.class)
                .eq(Achievement::getId, achievementAuthor.getAchievementId()));
        checkRoleUtil.checkPermissionAchievement(achievement.getStatus());

        boolean result = baseMapper.deleteById(achievementAuthor) == 1;
        if (result) {
            updateAllAuthor(achievement, achievementAuthor);
        }
        return result;
    }

    /**
     * 修改科研成果作者
     * @param achievementAuthor 科研成果作者信息
     * @return 修改操作是否成功
     */
    @Override
    public boolean updateAchievementAuthor(AchievementAuthor achievementAuthor) {
        Achievement achievement = achievementMapper.selectById(achievementAuthor.getAchievementId());
        checkRoleUtil.checkPermissionAchievement(achievement.getStatus());

        double newAssessment;
        try {
            newAssessment = Double.parseDouble(achievementAuthor.getAssessment());
        } catch (NumberFormatException e) {
            throw new BaseException("考核系数格式不正确");
        }
        if (newAssessment > 100 || newAssessment < 0) {
            throw new BaseException("输入数据应在0-100范围内");
        }
        String Pscore = "0.00";

        Achievement achievement1=iAchievementService.getAchievementById(String.valueOf(achievementAuthor.getAchievementId()));
//        if(achievement1 != null){
//            float finalValue = Float.parseFloat(achievement1.getScore());
//            // 计算并保留两位小数
//            double pscore = finalValue * newAssessment / 100.0;
//            Pscore = DECIMAL_FORMAT.format(pscore);
//        }
        String scoreStr = achievement.getScore();
        if (scoreStr != null && !scoreStr.trim().isEmpty()) {
            try {
                float finalValue = Float.parseFloat(scoreStr.trim());
                double pscore = finalValue * newAssessment / 100.0;
                Pscore = DECIMAL_FORMAT.format(pscore);
            } catch (NumberFormatException e) {
                Pscore = "0.00";
            }
        } else {
            Pscore = "0.00";
        }

        // 查询该科研成果的所有作者
        List<AchievementAuthor> achievementAuthorList = listAuthor(String.valueOf(achievementAuthor.getAchievementId()));

        // 判断加起来总分是否超过100
        double sum = 0;
        for (AchievementAuthor author : achievementAuthorList) {
            if(!StrUtil.isBlank(author.getAssessment())){
                    sum += Double.parseDouble(author.getAssessment());
            }
        }
        if (sum - Double.parseDouble(getOne(Wrappers.lambdaQuery(AchievementAuthor.class)
                .eq(AchievementAuthor::getAchievementAuthorId, achievementAuthor.getAchievementAuthorId())).getAssessment()) + newAssessment > 100) {
            throw new BaseException("该科研成果的作者总分和超过100");
        }

        achievementAuthor.setPscore(Pscore);

        boolean result = baseMapper.updateById(achievementAuthor) == 1;
        if (result) {
            updateAllAuthor(achievement, achievementAuthor);
        }
        return result;
    }

    /**
     * 获取科研成果作者
     * @param id 科研成果ID
     * @return 科研成果作者列表
     */
    @Override
    public List<AchievementAuthor> listAuthor(String id) {
        List<AchievementAuthor> list = baseMapper.selectList(Wrappers.lambdaQuery(AchievementAuthor.class)
                .eq(AchievementAuthor::getAchievementId, id));
        list.sort(Comparator.comparingInt(p -> AUTHOR_TYPE_ORDER.indexOf(p.getAuthortype())));
        return list;
    }



    /**
     * 维护AllAuthor字段
     * @param achievement 科研成果对象
     * @param achievementAuthor 当前操作的作者
     */
    private void updateAllAuthor(Achievement achievement, AchievementAuthor achievementAuthor) {
        if (Objects.isNull(achievement)) {
            throw new BaseException("科研成果信息不完整，无法更新作者信息");
        }

        // 1. 先清除原来的AllAuthor相关字段
        achievement.setAllAuthor(null);
        achievement.setAllAuthorName(null);
        iAchievementService.updateById(achievement);

        // 2. 查询该科研成果的所有作者
        List<AchievementAuthor> allAuthorList = listAuthor(String.valueOf(achievement.getId()));

        // 3. 按照作者类型排序
        allAuthorList.sort(Comparator.comparingInt(p -> AUTHOR_TYPE_ORDER.indexOf(p.getAuthortype())));

        // 4. 提取工号集合（可能为空）
        List<String> userAccountList = allAuthorList.stream()
                .map(AchievementAuthor::getUserAccount)
                .filter(Objects::nonNull) // 过滤空工号
                .collect(Collectors.toList());

        // 关键修改：检查工号集合是否为空，避免IN()语法错误
        List<User> userList = new ArrayList<>();
        if (!userAccountList.isEmpty()) { // 只有当集合非空时才执行查询
            userList = iUserService.list(Wrappers.lambdaQuery(User.class)
                    .in(User::getAccount, userAccountList));
        }

        // 后续逻辑保持不变
        List<String> uidList = userList.stream()
                .map(User::getUid)
                .collect(Collectors.toList());
        List<String> nameList = userList.stream()
                .map(User::getName)
                .collect(Collectors.toList());

        String allAuthor = String.join(",", uidList);
        achievement.setAllAuthor(allAuthor);
        achievement.setAllAuthorName(String.join(",", nameList));
        iAchievementService.updateById(achievement);

//        // 1. 先删除原来的AllAuthor字段
//        achievement.setAllAuthor(null);
//        iAchievementService.updateById(achievement);
//
//        // 2. 查询该科研成果的所有作者
//        List<AchievementAuthor> allAuthorList = listAuthor(String.valueOf(achievement.getId()));
//        // 3. 按照作者类型排序
//        allAuthorList.sort(Comparator.comparingInt(p -> AUTHOR_TYPE_ORDER.indexOf(p.getAuthortype())));
//        // 4. 根据工号集合查询用户的主键id
//        List<String> userAccountList = allAuthorList.stream()
//                .map(AchievementAuthor::getUserAccount)
//                .collect(Collectors.toList());
//        List<User> userList = iUserService.list(Wrappers.lambdaQuery(User.class)
//                .in(User::getAccount, userAccountList));
//        List<String> uidList = userList.stream()
//                .map(User::getUid)
//                .collect(Collectors.toList());
//        //筛选出用户的名字集合
//        List<String> nameList = userList.stream()
//                .map(User::getName)
//                .collect(Collectors.toList());
//        // 5. 将主键id拼接成字符串
//        String allAuthor = String.join(",", uidList);
//        //更新AllAuthorName字段
//        achievement.setAllAuthorName(String.join(",", nameList));
//        // 6. 更新AllAuthor字段
//        achievement.setAllAuthor(allAuthor);
//        iAchievementService.updateById(achievement);
    }
}

